﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Xml.Serialization;

namespace SQLDeployAnything.Data.Environment
{
    [Serializable]
    [XmlRoot(ElementName="Connection")]
    public class Connection : INotifyPropertyChanged
    {
        private string mName;

        [XmlAttribute(AttributeName="Name")]
        public string ConnectionName { get { return mName; } 
            set 
            {
                if (value != mName)
                {
                    mName = value;
                    OnPropertyChanged("ConnectionName");
                }
            } 
        }

        protected virtual bool Validate(){ return false;}

        public event PropertyChangedEventHandler PropertyChanged;
        protected internal void OnPropertyChanged(string name)
        {
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null)
                handler(this, new PropertyChangedEventArgs(name));
        }

        [XmlIgnore]
        public virtual string ConnectionTypeHeading { get; protected internal set; }

        [XmlIgnore]
        public virtual string ConnectionDetails { get; protected internal set; }

        private static List<ConnectionType> sTypes = null;
        private static object sTypeLocks = new object();

        public class ConnectionType
        {
            internal ConnectionType(Type type)
            {
                Object obj = Activator.CreateInstance(type);
                if (!(obj is Connection))
                    throw new ArgumentException();

                Connection con = (Connection)obj;
                Name = con.ConnectionTypeHeading;
                ObjectType = type;
            }

            public string Name
            {
                get;
                private set;
            }

            public Type ObjectType
            {
                get;
                private set;
            }
        }
        public static List<ConnectionType> AvailableConnectionTypes()
        {
            lock (sTypeLocks)
            {
                if (sTypes == null)
                {
                    sTypes = new List<ConnectionType>();
                    //TODO see if we can't use reflection so we can do this automaticly later...
                    sTypes.Add(new ConnectionType(typeof(SQLConnection)));
                    sTypes.Add(new ConnectionType(typeof(SSISConnection)));
                    sTypes.Add(new ConnectionType(typeof(LoggingConnection)));
                }
            }
            return sTypes;
        }
    }
}
